<template>
  <div>
    <FosoCard :showheader="false" class="h-[1180px]">
      <div class="flex items-center">
        <div class="w-[15%] text-xs">
          {{ $t('sys.department.departmentList') }}
        </div>
        <div class="ml-3 w-[80%]">
          <el-input
            v-model="searchValue"
            :placeholder="$t('common.search')"
            class="input-with-select"
          >
            <template #append>
              <el-button :icon="Search" />
            </template>
          </el-input>
        </div>
        <div class="ml-3">
          <el-dropdown>
            <el-icon><Operation /></el-icon>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="expandAllHandle('open')">
                  {{ $t('sys.department.expandAll') }}
                </el-dropdown-item>
                <el-dropdown-item @click="expandAllHandle('close')">
                  {{ $t('sys.department.collapseAll') }}
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </div>
      <el-tree
        :key="treeKey"
        :data="options"
        :default-expand-all="isExpandAll"
        :icon="Plus"
        :props="defaultProps"
        class="mt-5"
        node-key="id"
        @node-click="searchDepartment"
      />
    </FosoCard>
  </div>
</template>

<script setup lang="ts">
import { $t } from '@vben/locales';

import { Operation, Plus, Search } from '@element-plus/icons-vue';

import { refreshDictOptions } from '#/hooks/useDictCache';
// 定义 emit 类型
interface Emit {
  (e: 'searchDepartment', data?: any): void;
}
// 创建 emit 函数
const emit = defineEmits<Emit>();
const options = ref<any[]>([]); // 下拉数据
const treeKey = ref(1); // 必须绑定一个组件key,才能确保展开与收缩有效果！
const isExpandAll = ref<boolean>(false);
const treeOptions = ref<any[]>([]); // 临时保存一份树配置的数据,用于搜索
const searchValue = ref<string>(''); // 搜索框的值
const defaultProps = {
  children: 'children',
  label: 'label',
  id: 'id',
};

/** 展开与收缩 */
const expandAllHandle = async (type: string) => {
  nextTick(() => {
    treeKey.value = Date.now();
    type === 'open' ? (isExpandAll.value = true) : (isExpandAll.value = false); // 展开与收缩
  });
};
// const formdata = ref({
//   status: 1,
//   name: '徐坤老⑦',
//   parentId: 29,
//   leader: '徐坤1',
//   phone: '11111',
//   email: '333@qq.com',
//   sort: 1,
// });
// const addHandle = async () => {
//   await createDepartment(formdata.value); // 新增
//   refreshDictOptions('department');
//   useDictOptions('department');
// };
const searchDepartment = (data: any) => {
  emit('searchDepartment', data);
};
// console.log(aa.value);

onMounted(async () => {
  options.value = await refreshDictOptions('department'); // 更新数据
  treeOptions.value = options.value; // 赋值给下拉数据
});

/**
 * 在树形数据中搜索匹配关键字的节点
 * @param treeData 要搜索的树形数据
 * @param keyword 搜索关键词
 * @returns 包含所有匹配节点的扁平化数组
 */
const searchNodes = (treeData: any, keyword: any) => {
  const searchNodesInTree = ref<any[]>([]); // 搜索结果

  const traverseAndSearch = (data: any) => {
    for (const item of data) {
      const { label, children } = item;
      if (label.includes(keyword)) {
        searchNodesInTree.value.push(item);
      }
      if (children) {
        traverseAndSearch(children); // 递归处理子节点
      }
    }
  };

  traverseAndSearch(treeData);
  return searchNodesInTree.value; // 返回处理后的结果
};
// // 确保下拉数据数据拿到
watch(
  () => searchValue.value,
  (val: any) => {
    options.value = searchNodes(treeOptions.value, val); // 监听搜索框的值
  },
);
</script>

<style scoped lang="scss">
:deep() .el-tree-node {
  border-bottom: 1px solid #eee !important;
}
</style>
